class UserController < ApplicationController
	skip_before_action :require_login, only: [:register, :signin]
	def register
		@user = User.new(user_params)
		if !@user.valid?
			status = 'error'
			info = {error:@user.errors.messages}
		else
		  if @user.save
			status = 'ok'
			info = {userid:@user.id, username:@user.username}
		  else
			status = 'error'
			info = {error:@user.errors.messages}
		 end
		end
		render json: {status:status, type:'account', currentAuthority:'guest', info:info}
	end

	def signin # 登录
		@user = User.find_by(username: params[:username])
		# puts @user
		if @user && @user.authenticate(params[:password])
			session[:user_id] = @user.id
			session[:user_name] = @user.username
			render json: {status:'ok',type:'account', currentAuthority:'user', info:{userid:@user.id,username:@user.username}}
		else 
			render json: {status:'error',type:'account', currentAuthority:'guest', info:{error:'username or password not correct!'}}
		end
	end

	# before_action :require_user
	def signout # 注销
		# @user = User.find_by(username: session[:user_name])
		# if @user && (@user.id == session[:user_id])
		if current_user
			session[:user_id] = nil
			session[:user_name] = nil
			render json: {status:'ok',type:'account', currentAuthority:'guest', info:{info:'success'}}
		else
			render json: {status:'error',type:'account', currentAuthority:'guest', info:{error:'fail'}}
		end
	end

	def getinfo
		if current_user
			@user = User.find_by(username: session[:user_name])
			render json: {status:'ok',type:'account', currentAuthority:'user', info:{id:@user.id, username:@user.username, email:@user.email}}
		else
			render json: {status:'error',type:'account', currentAuthority:'guest', info:{error:'fail'}}
		end
	end
	    

	private 
	def user_params
	    params.require(:user).permit(:username,:email,:password)
	end

end
